#encoding=utf-8
from actionModule.handle import base
from base.common import retSuccess, execMysql
from config.db.models import Field
from config.settings import PROJECT_PATH

formJson = [
      {'id':'id', 'key':'Hidden', 'name':'主键'},
      {'id':'name', 'key':'Input', 'name':'名称', 'noNull':True},
      {'id':'package', 'key':'Input', 'name':'包', 'noNull':True},
      {'id':'remark', 'key':'Input', 'name':'备注', 'noNull':True},
      {'id':'fields','key':'Field', 'name':'字段', 'noNull':True,'detail_key':'Textarea'},
      {'key':'Submit', 'action':'table.create','back':'closeTab'},
]
filePath=PROJECT_PATH+"/yqy/html/templates/"
tempPath=PROJECT_PATH+"/yqy/html/templates/"
class table(base):
    def __init__(self):
        self.formJson=formJson
        
    def saveField(self):
        item = Field()
        item.setAttr("field", self.json['id'])
        item.setAttr("key","component/"+self.json['name']+".js")
        item.save()
        self.json["id"]=item.id
        self.json['name']=item.key
        #创建文件
        try:
            tempFile=open(filePath+item.key,"rb")
        except Exception:
            tempFile=open(filePath+item.key,"wb")    
        tempFile.close()
        return self.json
    def queryField(self):
        key=self.json["name"]
        return execMysql("SELECT id,db_field.key as text from db_field where field='"+key+"'")
        
    def getFile(self):
        name=self.getPost("name")
        file=open("%s%s"%(tempPath,name),"rb")
        text=file.read()
        file.close()
        return {"text":text}
    def saveFile(self):
        name=self.getPost("name")
        content=self.getPost("text")
        file=open("%s%s"%(tempPath,name),"wb")
        file.write(content)
        file.close()
        return retSuccess("修改成功")
    def delField(self):
        arr=self.json["str_array"]
        for item in arr:
            Field.objects.get(id=item).delete()
        return retSuccess("删除成功")